package util;

public class ByteUtil {

    /***
     * 将int转成长度为4的byte数组（在java中int为32位，所以就是4byte）
     * @param i
     * @return
     */
    public static byte[] intToBytes(int i) {
        byte[] result = new byte[4];
        result[0] = (byte) ((i >> 24) & 0xFF);
        result[1] = (byte) ((i >> 16) & 0xFF);
        result[2] = (byte) ((i >> 8) & 0xFF);
        result[3] = (byte) (i & 0xFF);
        return result;

    }

    /***
     * 将int转成长度为2的byte数组
     * @param i
     * @return
     */
    public static byte[] intToByte2(int i) {
        byte[] result = new byte[2];
        result[0] = (byte) ((i >> 8) & 0xFF);
        result[1] = (byte) (i & 0xFF);
        return result;

    }

    /***
     * 将byte数组转换为int型数据
     * @param bytes
     * @return
     */
    public static int bytesToInt(byte[] bytes) {
        int value=0;
        for(int i = 0; i < 4; i++) {
            int shift= (3-i) * 8;
            value +=(bytes[i] & 0xFF) << shift;
        }
        return value;
    }

    /***
     * 将2byte数组转换为int型数据
     * @param bytes
     * @return
     */
    public static int byte2ToInt(byte[] bytes) {
        int value=0;
        for(int i = 0; i < 2; i++) {
            int shift= (1-i) * 8;
            value +=(bytes[i] & 0xFF) << shift;
        }
        return value;
    }

    /***
     * 将long转换成byte数组
     * @param l
     * @return
     */
    public static byte[] longToBytes(long l){
        long temp = l;
        byte[] b = new byte[8];
        for(int i =0; i < b.length; i++){
            b[i]=new Long(temp &0xff).byteValue();//将最低位保存在最低位
            temp = temp >>8;// 向右移8位
        }
        return b;
    }

    /***
     * 将byte数组转换成long
     * @param b
     * @return
     */
    public static long bytesToLong(byte[] b){
        long s =0;
        long s0 = b[0]&0xff;// 最低位
        long s1 = b[1]&0xff;
        long s2 = b[2]&0xff;
        long s3 = b[3]&0xff;
        long s4 = b[4]&0xff;// 最低位
        long s5 = b[5]&0xff;
        long s6 = b[6]&0xff;
        long s7 = b[7]&0xff;
        // s0不变
        s1 <<=8;
        s2 <<=16;
        s3 <<=24;
        s4 <<=8*4;
        s5 <<=8*5;
        s6 <<=8*6;
        s7 <<=8*7;
        s = s0 | s1 | s2 | s3 | s4 | s5 | s6 | s7;
        return s;
    }
}
